package com.example.dakotanews.controller;

import com.example.dakotanews.dto.utils.ApiResponse;
import com.example.dakotanews.dto.utils.ResponseCode;
import com.example.dakotanews.service.IssueService;
import com.example.dakotanews.utils.JwtUtil;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/issue")
public class IssueController {

    private final IssueService issueService;
    private final JwtUtil jwtUtil;

    public IssueController(
            IssueService issueService,
            JwtUtil jwtUtil
    ) {
        this.issueService = issueService;
        this.jwtUtil = jwtUtil;
    }

    /**
     * 公有接口
     * @description 获取全部话题
     * @return 返回话题记录列表
     */
    @GetMapping("/getAllIssues")
    public ApiResponse<Object> getAllIssues() {
        return issueService.getAllIssues();
    }

    /**
     * @description 添加话题，为新话题创建记录。完全私有接口
     * @param issueName 话题名称
     * @param jwt 检查是否为登录用户的请求
     * @return 操作结果
     */
    @GetMapping("/addIssue")
    public ApiResponse<Object> addIssue(
            @RequestParam String issueName,
            @RequestHeader(value = "Authorization", required = false)String jwt) {

        Integer userId = jwtUtil.extractUserIdFromJWT(jwt);
        if (userId == null) {
            return new ApiResponse<>(ResponseCode.UNAUTHORIZED, "未授权的请求", "请先登录");
        }

        return issueService.addIssue(issueName);
    }
}
